package com.edu.servlet;

import com.edu.entity.User;
import com.edu.entity.productOrder;
import com.edu.service.impl.productOrderServiceImpl;
import com.edu.service.productOrderService;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;

@WebServlet("/order")
public class ProductOrderServlet extends HttpServlet {
    private static final Logger logger = Logger.getLogger(ProductOrderServlet.class.getName());
    private productOrderService orderService = new productOrderServiceImpl();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        HttpSession session = request.getSession(false);
        
        User u = (User) session.getAttribute("logInUser");
        Integer sellerId = u.getUserid();
        
        int type = 0;
        
        try {
            String typeParam = request.getParameter("type");
            if (typeParam != null && !typeParam.isEmpty()) {
                type = Integer.parseInt(typeParam);
            }
            
            logger.info("获取订单请求: sellerId=" + sellerId + ", type=" + type);
            
            List<productOrder> orders = orderService.getAll(sellerId, type);
            logger.info("查询到订单数量: " + orders.size());
            
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            new ObjectMapper().writeValue(response.getWriter(), orders);
           
        } catch (Exception e) {
            logger.severe("获取订单失败: " + e.getMessage());
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("{\"error\":\"服务器内部错误\"}");
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}